<template>
    <div :id="id" :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from "echarts";
import resize from "./mixins/resize";

export default {
    mixins: [resize],
    props: {
        className: {
            type: String,
            default: "chart",
        },
        id: {
            type: String,
            default: "chart",
        },
        width: {
            type: String,
            default: "200px",
        },
        height: {
            type: String,
            default: "200px",
        },
        title: {
            type: String,
            default: "图表",
        },
        chartData: {
            type: Object,
            default: function () {
                return {
                    data: [],
                    type: 'pie',
                    groups: [],//分组项
                }
            }
        },
    },
    data () {
        return {
            chart: null,
        };
    },
    mounted () {
        this.initChart();
    },
    beforeDestroy () {
        if (!this.chart) {
            return;
        }
        this.chart.dispose();
        this.chart = null;
    },
    watch: {
        chartData: {
            deep: true,
            handler (val) {
                this.selfSetOption();
            },
        },
    },
    methods: {
        initChart () {
            this.chart = echarts.init(document.getElementById(this.id));
            this.selfSetOption();
        },
        resetChart () {
            if (this.chart) {
                this.chart.clear();
                this.selfSetOption();
                this.chart.resize();
            } else {
                this.initChart();
            }
        },
        selfSetOption () {
            let nOption = {}
            let option = {
                grid: {
                    top: "10%",
                    left: "5%",
                    right: "5%",
                    bottom: "15%"
                },
            };
            if (this.chartData.type == 'pie') {
                nOption = {
                    tooltip: {
                        trigger: "item",
                        formatter: function (p) {
                            let str = `
                                <div>${p.name}</div>
                                <div>${p.marker} ${p.value}(${p.percent}%)</div>
                                `;
                            return str;
                        },
                    },
                    legend: {
                        type: "scroll",
                        bottom: 0,
                        textStyle: {
                            color: "#67729d",
                        },
                        selector: [
                            {
                                type: 'all',
                                // 可以是任意你喜欢的 title
                                title: '全选'
                            },
                            {
                                type: 'inverse',
                                title: '反选'
                            }
                        ],
                    },
                    series: {
                        type: "pie",
                        data: this.chartData.data,
                        radius: ["40%", "70%"],
                        itemStyle: {
                            borderRadius: 5,
                            borderColor: "#fff",
                            borderWidth: 2,
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: "15",
                                fontWeight: "bold",
                            },
                        },
                    }
                }
            } else if (this.chartData.type == 'bar') {
                //分组项第一项作为x轴
                let xField = this.chartData.groups[0].field
                let xData = this.chartData.data.map(d => {
                    return d.baseData[xField]
                })
                xData = [...new Set(xData)]

                //其他项组成series
                let fieldArr = this.chartData.groups.filter((g, i) => {
                    return i != 0
                }).map(g => g.field)

                //给每项数据加上keyName 除分组项第一项 通过 - 连接
                let copyData = this.chartData.data.map(d => {
                    let keyName = fieldArr.map(f => {
                        return d.baseData[f]
                    }).join("-")
                    d.keyName = keyName
                    return d
                })

                //组装serie name数组
                let barData = copyData.map(d => {
                    return fieldArr.map(f => {
                        return d.baseData[f]
                    }).join("-")
                })

                //字符串数组去重
                barData = [...new Set(barData)]

                //组装serie 数组
                barData = barData.map(serieName => {
                    let series = {
                        name: serieName,
                        type: 'bar',
                        stack: 'Ad', //默认堆叠图
                        barGap: 0,
                        emphasis: {
                            focus: 'series'
                        },
                        data: []
                    }
                    series.data = xData.map(x => {
                        let fData = copyData.find(d => {
                            return d.baseData[xField] == x && d.keyName == serieName
                        })
                        if (fData) {
                            return {
                                percent: fData.percent,
                                value: fData.value
                            }
                        }
                        return {
                            value: null
                        }
                    })
                    return series
                })
                nOption = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                        enterable: true,
                        confine: true,
                        formatter: function (arr) {
                            let str = `<div style="margin-bottom:5px;">${arr[0].name}</div>`;
                            arr.forEach(item => {
                                if (item.value) {
                                    str += `<div style="margin-bottom:5px">
                                    <div style="display:flex;justify-content:space-between">
                                        <div style="flex:5;margin-right:10px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden" title="${item.seriesName}">
                                            <span>${item.marker}</span>
                                            <span>${item.seriesName}</span>
                                        </div>
                                        <div style="flex:3;text-align:center;margin-right:10px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden" title="${item.value}">
                                            <span style="font-weight:bold">${item.value}</span>
                                        </div>
                                        <div style="flex:1;">
                                            <span style="font-weight:bold">${item.data.percent}</span>
                                        </div>
                                    </div>
                                </div>`
                                }

                            })
                            let res = `<div style="max-height:350px;width:300px;overflow:auto;padding-right:10px;">${str}</div>`
                            return res;
                        },
                    },
                    toolbox: {
                        show: true,
                        orient: 'vertical',
                        left: 'right',
                        top: 'center',
                        feature: {
                            mark: { show: true },
                            magicType: { show: true, type: ['line', 'bar', 'stack'] },
                            restore: { show: true },
                        }
                    },
                    xAxis: [
                        {
                            type: 'category',
                            name: this.chartData.groups[0].title,
                            axisTick: { show: false },
                            data: xData,
                        }
                    ],
                    yAxis: [
                        {
                            name: "用户数",
                            type: 'value'
                        }
                    ],
                    dataZoom: [
                        {
                            show: true,
                            height: 15,
                            xAxisIndex: [
                                0
                            ],
                            handleStyle: {
                                color: '#d3dee5'
                            },
                            borderColor: '#90979c'

                        },
                        {
                            type: 'inside',
                            show: true,
                            height: 15,
                            start: 1,
                            end: 35
                        }
                    ],
                    series: barData
                }
            }
            Object.assign(option, nOption)
            this.chart.setOption(option, {
                notMerge: true
            });
        },
    },
};
</script>
